<?php

namespace app\index\controller;

use think\Session;
use think\Request;
use think\Cache;
use think\Config;
use think\Db;
use think\Controller;
use \CFormat;
use think\View;

class Product extends Controller {
    // 视图类实例
    protected $view;
    // Request实例
    protected $request;

    public function __construct()
    {
        parent::__construct();

        if (null === $this->view) {
            $this->view = View::instance(Config::get('template'), Config::get('view_replace_str'));
        }
        if (null === $this->request) {
            $this->request = Request::instance();
        }
        // 用户ID
        defined('UID') or define('UID', Session::get(Config::get('rbac.user_auth_key')));
    }
    
    //商品列表
    public function index(){
        $preid = input('param.preid', 0);
        $subid = input('param.subid', 0);
        $key = input('param.key', '');
        $where=array();
        if($subid){
            $where['p.class_id'] = $subid;
        }
        if($key){
            $where['p.name'] = ['LIKE', '%'.$key.'%'];
        }
        $where['p.status'] = ['<>', 0];
        $products = $this->_get_products($where);
        $page = $products->render();
        if($products){
            $this->view->assign('products', $products);
            $this->view->assign('page', $page);
        }
        return $this->view->fetch();
    }
    
    //商品详细信息
    public function show(){
        $pid = input('param.pid', 0);
        $product = Db::name('product')
                ->alias('p')
                ->join('stock st', 'p.id=st.pid', 'LEFT')
                ->join('product_class pc', 'p.class_id=pc.id', 'LEFT')
                ->field('p.id AS pid,p.name AS pname,p.barcode,p.class_id AS subid,pc.parent AS preid,p.supplier_id AS suid,p.unit,p.purchase_price AS pprice,p.price,'
                        . 'st.id AS stid,st.stock_warehouse AS w_stock,st.stock_shelf AS s_stock,st.threshold,p.production_date AS prodate,p.shelf_life AS life,'
                        . 'p.valid_until AS until,p.warning_day AS warning,p.remarks')
                ->find($pid);
        if($product){
            $product['prodate'] = CFormat::FormatDate($product['prodate'], 'Y-m-d');
            $product['life']    = CFormat::FormatToDay($product['life']);
            $product['until']   = CFormat::FormatDate($product['until'], 'Y-m-d');
            $product['warning']    = CFormat::FormatToDay($product['warning']);
        }
        $this->view->assign('product', $product);
        return $this->view->fetch();
    }
    
    //商品删除
    public function delete(){
        $pid = input('param.pid', 0);
        if(!$pid){
            return ajax_return_adv_error('商品分类不存在');
        }
        Db::name('product')->where('id', $pid)->update(['status'=>0]);
        return ajax_return_adv('操作成功');
    }
    
    //新增&修改商品
    public function addOrUpdate(){
        $product = input('param.', array());
        if($product){
            $product['production_date'] = strtotime($product['production_date']);
            if($product['shelf_life']){
                $product['shelf_life'] = \CFormat::FormatToTime($product['shelf_life']);
                $product['valid_until'] = $product['shelf_life']+$product['production_date'];
            }
            else if(!$product['valid_until']){
                $product['valid_until'] = strtotime($product['valid_until']);
                $product['shelf_life'] = $product['production_date']-$product['valid_until'];
            }
            else{
                return ajax_return_adv_error('保质期和有效期至不能全为空！');
            }
            $pro=array(
                'class_id'          => $product['subid'],
                'name'              => $product['name'],
                'unit'              => $product['unit'],
                'supplier_id'       => $product['supplier_id'],
                'remarks'           => $product['remarks'],
                'barcode'           => $product['barcode'],
                'purchase_price'    => $product['purchase_price'],
                'price'             => $product['price'],
                'production_date'   => $product['production_date'],
                'shelf_life'        => $product['shelf_life'],
                'valid_until'       => $product['valid_until'],
                'warning_day'       => \CFormat::FormatToTime($product['warning_day'])
            );
            if($product['id']){
                Db::name('product')->where('id',$product['id'])->update($pro);
//                var_dump($a->getLastSQL());exit;
            }
            else{
                $pro['image'] = '';
                $pro['status'] = 1;
                $pro['gen_time'] = time();
                $product['id'] = Db::name('product')->insertGetId($pro);
            }
            $sto=array(
                'pid'			=> $product['id'],
                'stock_warehouse'	=> $product['w_stock'],
                'stock_shelf'		=> $product['s_stock'],
                'threshold'		=> $product['threshold']
            );
            if($product['stid']){
                Db::name('stock')->where('id', $product['stid'])->update($sto);
            }
            else{
                $product['stid'] = Db::name('stock')->insertGetId($sto);
            }
            Db::name('product')->where('id', $product['id'])->update(['stock_id'=>$product['stid']]);
            return ajax_return_adv('操作成功');
        }
        else{
            return ajax_return_adv_error('操作失败！');
        }
    }
    
    //商品分类列表，仅显示二级分类
    public function classShow() {
        $productClass = Db::name('product_class')
                ->alias('pc')
                ->join('product_class pa', 'pc.parent=pa.id')
                ->field('pc.id AS cid,pc.name,pa.name AS parent,pc.introduce,pc.remarks')
                ->where('pa.status', '<>', 0)
                ->where('pc.status', '<>', 0)
                ->order('pc.parent ASC')
                ->select();
        if($productClass){
            foreach ($productClass as $_k=>$_v){
                if(!$_v['introduce']){
                    $productClass[$_k]['introduce'] = '无';
                }
                if(!$_v['remarks']){
                    $productClass[$_k]['remarks'] = '无';
                }
            }
            $this->view->assign('class', $productClass);
        }
        return $this->view->fetch();
    }
    
    //获取单个商品分类信息
    public function classGet(){
        $cid = input('get.cid', 0);
        $class = Db::name('product_class')->field('id AS cid,name,parent,introduce,remarks')->find($cid);
        $this->view->assign('class', $class);
        return $this->view->fetch();
    }
    
    //获取一级分类列表，用于下拉框
    public function preClass(){
        $preclass= Db::name('product_class')->where('level', 1)->where('status', '<>', 0)->field('id AS preid,name AS prename')->select();
        return ding_json(0, 'OK', $preclass);
    }
    
    //获取一、二级分类列表，用于下拉框
    public function allClass(){
        $preclass= Db::name('product_class')->where('level', 1)->field('id AS preid,name AS prename')->select();
        foreach ($preclass as $_k=>$_v){
            $subclass = Db::name('product_class')->where('parent',$_v['preid'])->where('status', '<>', 0)->field('id AS subid,name AS subName')->select();
            $preclass[$_k]['subclass'] = $subclass;
        }
        return ding_json(0, 'OK', $preclass);
    }
    
    //商品分类删除
    public function classDel(){
        $cid = input('get.cid', 0);
        if(!$cid){
            return ajax_return_adv_error('商品分类不存在');
        }
        Db::name('product_class')->where('id', $cid)->update(['status'=>0]);
        return ajax_return_adv('操作成功');
    }
    
    //分类新增&修改
    public function classAddUpdate(){
        $class = input('post.',array());
        if($class){
            if($class['parent']){
                $class['level'] = 2;
            }
            else{
                $class['level'] = 1;
            }
            $class['status'] = 1;
            if($class['id']){
                Db::name('product_class')->update($class);
            }
            else{
                Db::name('product_class')->insert($class);
            }
            return ajax_return_adv('操作成功');
        }
        else{
            return ajax_return_adv_error('操作失败！');
        }
    }
    
    //商品列表
    public function stockIndex(){
        $preid = input('param.preid', 0);
        $subid = input('param.subid', 0);
        $key = input('param.key', '');
        $where=array();
        if($subid){
            $where['p.class_id'] = $subid;
        }
        if($key){
            $where['p.name'] = ['LIKE', '%'.$key.'%'];
        }
        $where['p.status'] = ['<>', 0];
        $products = $this->_get_products($where);
        $page = $products->render();
        if($products){
            $this->view->assign('products', $products);
            $this->view->assign('page', $page);
        }
        return $this->view->fetch();
    }
    
    //商品详情
    public function stockItem(){
        $pid = input('param.pid', 0);
        $type = input('param.type', 0);
        $product = Db::name('product')
                ->alias('p')
                ->join('stock st', 'p.id=st.pid', 'LEFT')
                ->join('product_class pc', 'p.class_id=pc.id', 'LEFT')
                ->field('p.id AS pid,p.name AS pname,pc.name AS cname,p.unit,p.barcode,'
                        . 'st.id AS stid,st.stock_warehouse AS w_stock,st.stock_shelf AS s_stock')
                ->find($pid);
        if(!$product){
            return ajax_return_adv_error('未获取到商品信息');
        }
        if($type==1){
            $sttype = '入库';
        }
        else{
            $sttype = '出库';
        }
        $this->view->assign('product', $product);
        $this->view->assign('sttype', $sttype);
        $this->view->assign('type', $type);
        return $this->view->fetch();
    }
    
    //出入库
    public function stockEdit(){
        $pid = input('param.pid', 0);
        $type = input('param.type', 0);
        $count = input('param.count',0);
        $remarks = input('param.remarks', '');
        if(!$pid||!$type){
            return ajax_return_adv_error('操作失败');
        }
        if($type==1){
            Db::name('stock')->where('pid', $pid)->setInc('stock_warehouse', $count);
        }
        else{
            Db::name('stock')->where('pid', $pid)->setDec('stock_warehouse', $count);
            Db::name('stock')->where('pid', $pid)->setInc('stock_shelf', $count);
        }
        Db::name('stock_out_incom')->insert(['pid'=>$pid, 'type'=>$type, 'count'=>$count, 'gen_time'=> time(), 'sid'=>UID , 'remarks'=>$remarks]);
        return ajax_return_adv();
    }
    
    //出入库日志
    public function stockLog(){
        $startdate= input('post.startdate');
        $enddate= input('post.enddate');
        
        $time= time();
        $start= strtotime($startdate);
        $end= strtotime($enddate)+3600*24;
        $today = strtotime(date('Y-m-d', $time));  //获取今天0时0分0秒的时间戳
        
        $where = array();
        if(!$startdate&&!$enddate){
            $where['sl.gen_time'] = ['>=', $today];
        }
        else if(!$startdate&&$enddate) {
            $where['sl.gen_time'] = ['<', $end];
        }
        else if(!$enddate&&$startdate) {
            $where['sl.gen_time'] = ['>=', $start];
        }
        else {
            if($startdate > $enddate){
                return ajax_return_adv_error('开始时间不能大于结束时间');
            }
            $where['sl.gen_time'] = ['>=', $start];
            $where['sl.gen_time'] = ['<', $end];
        }
        
        $stocklog = Db::name('stock_out_incom')
                ->alias('sl')
                ->join('product p', 'sl.pid=p.id', 'LEFT')
                ->join('staff s', 'sl.sid=s.id', 'LEFT')
                ->field('p.name AS pname,sl.type,s.name AS sname,p.unit,sl.count,sl.gen_time AS gentime,sl.remarks')
                ->where($where)
                ->paginate(15);
        $page = $stocklog->render();
        $this->view->assign('start', $startdate);
        $this->view->assign('end', $enddate);
        $this->view->assign('stocklog', $stocklog);
        $this->view->assign('page', $page);
        return $this->view->fetch();
    }
    
    private function _get_products($where){
        $products = Db::name('product')
                ->alias('p')
                ->join('product_class pc', 'p.class_id=pc.id', 'LEFT')
                ->join('stock st', 'p.id=st.pid', 'LEFT')
                ->join('supplier su', 'p.supplier_id=su.id', 'LEFT')
                ->where($where)
                ->field('p.id AS pid,p.name AS pname,pc.name AS cname,p.barcode,su.name AS suname,p.unit,p.purchase_price AS pprice,p.price,'
                        . 'st.stock_warehouse AS w_stock,st.stock_shelf AS s_stock,p.valid_until AS until,p.remarks')
                ->order('p.gen_time DESC')
                ->paginate(15);
        return $products;
    }
}

